<template>
  <div class="table">
    <div class="search">
      <a-form-model layout="inline">
        <div class="fold">
          <a-form-model-item label="本机IP：" placeholder="请输入">
            <a-input></a-input>
          </a-form-model-item>
          <!-- <a-form-model-item label="昵称：" placeholder="请输入">
            <a-input></a-input>
          </a-form-model-item> -->
          <a-form-model-item label="钱包地址：" placeholder="请输入">
            <a-input></a-input>
          </a-form-model-item>
          <a-form-model-item>
            <span style="margin-top: 3px;">
              <a-button type="primary">查询</a-button>
              <a-button style="margin-left: 8px">重置</a-button>
            </span>
          </a-form-model-item>
          <a-form-model-item :wrapperCol="{ span: 24, offset: 15 }">
            <a-tooltip>
              <template slot="title">
                一键转账
              </template>
              <a-button type="primary" shape="circle" icon="credit-card" @click="showDialog('one')" />
            </a-tooltip>
            <a-tooltip>
              <template slot="title">
                一键质押
              </template>
              <a-button style="margin-left: 10px;" type="primary" shape="circle" icon="tool" @click="showDialog('two')" />
            </a-tooltip>
             <a-tooltip>
              <template slot="title">
                 批量解质押
              </template>
              <a-button style="margin-left: 10px;" type="primary" shape="circle" icon="block" @click="showDialog('six')" />
            </a-tooltip>
            <a-tooltip>
              <template slot="title">
                批量设置燃料费
              </template>
              <a-button style="margin-left: 10px;" type="primary" shape="circle" icon="setting"  @click="showDialog('three')" />
            </a-tooltip>
            <a-tooltip>
              <template slot="title">
                批量修改密码
              </template>
              <a-button style="margin-left: 10px;" type="primary" shape="circle" icon="control" @click="showDialog('four')" />
            </a-tooltip>
             <a-tooltip>
              <template slot="title">
                批量回滚区块
              </template>
              <a-button style="margin-left: 10px;" type="primary" shape="circle" icon="reload" @click="showDialog('seven')" />
            </a-tooltip>
            <a-tooltip>
              <template slot="title">
                批量解锁
              </template>
              <a-button style="margin-left: 10px;" type="primary" shape="circle" icon="unlock" @click="showDialog('five')" />
            </a-tooltip>
          </a-form-model-item>
        </div>
      </a-form-model>
    </div>
    <a-alert type="info" closable v-if="selectedRows.length !== 0">
      <span slot="message">
        已选择 <span style="color: red">{{ selectedRows.length }}</span>项
      </span>
    </a-alert>
    <advance-table 
      :columns="columns" 
      :data-source="dataSource" 
      title="矿机信息列表" 
      :loading="loading"
      rowKey="id"
      align="center"
      :row-selection="{ 
        selectedRowKeys: selectedRowKeys, 
        onChange: onSelectChange 
      }" 
      size="small"
      :format-conditions="true" 
      @search="onSearch"
      @refresh="onRefresh" 
      @reset="onReset"
      :pagination="false"
     >
      <!-- :pagination="{
        current: page,
        pageSize: pageSize,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: onPageChange,
        onShowSizeChange: onSizeChange,
      }" -->
      <template slot="local_ip" slot-scope="{text, record}">
        <a @click="showDrawer(text, record)">{{ text }}</a>
      </template>
      <template slot="send" slot-scope="{text}">
        {{text ? '是' : '否'}}
      </template>
      <template slot="address" slot-scope="{text}">
        <a-tooltip>
          <template slot="title">
            {{text}}
          </template>
          <div>{{text | subTen}}</div>
        </a-tooltip>
        <a-icon 
          type="copy" 
          data-clipboard-action="copy" 
          class="cobyOrderSn" 
          :data-clipboard-text="text"
          :style="{ color: '#40a9ff', cursor: 'pointer' }"
          @click="copyLink"
        >
        </a-icon>
      </template>
      <template slot="address" slot-scope="{text}">
        <a-tooltip placement="left">
          <template slot="title">
            点击复制
          </template>
          <div class="copyBtn" :data-clipboard-text="text" @click="copyCode">{{ text }}</div>
        </a-tooltip>
      </template>
      <template slot="privateKey" slot-scope="{text, record, index}">
          <a-icon 
            v-if="!record.keyStatus && record.privateKey.length !== 0" 
            type="eye-invisible"
            @click="showKey(record, index)"
          />
          <a-icon 
            v-else-if="record.privateKey.length !== 0"
            type="eye"
            @click="hideKey(record, index)"
          />

        <span v-if="!record.keyStatus">
            {{ text | hidePrKey }}
        </span>

        <a-tooltip placement="left" >
          <template slot="title">
            点击复制
          </template>
          <span v-if="record.keyStatus" class="copyBtn" :data-clipboard-text="text" @click="copyCode">
            {{ text }}
          </span>
        </a-tooltip>
      </template>

      <template slot="password" slot-scope="{text, record, index}">
        <span v-if="!record.passStatus">{{ text | hideInfo }}</span>
        <span v-else>{{ text }}</span>

        <a-icon v-if="!record.passStatus && record.password.length !== 0" @click="showPass(record.passStatus, index)" style="margin-left: 5px; cursor:pointer;" type="eye-invisible" />
        <a-icon v-else-if="record.password.length !== 0" @click="hidePass(record.passStatus, index)" style="margin-left: 5px; cursor:pointer;" type="eye" />
      </template>

      <template slot="millHeight" slot-scope="{record}">
        <a-popover placement="right">
          <template slot="content">
            <div>主网高度：{{ record.market }}</div><br />
            <div>矿机高度：{{ record.millHeight }}</div><br />
            <div>高度差：{{ record.heightCha }}</div>
          </template>
          
          <a-button v-if="record.heightCha > 5" type="danger">
            异 常
          </a-button>
          <a-button v-else type="primary">
            正 常
          </a-button>
        </a-popover>
      </template>
      <template slot="isPledge" slot-scope="{text}">
        <a-tag v-if="text == '1'" color="green">已质押</a-tag>
        <a-tag v-else color="orange"><span style="color: #fa8c16">未质押</span></a-tag>
      </template>
      <template slot="pledge" slot-scope="{text, record}">
        <a-button type="primary" shape="round" size="small" @click="showDrawer(text, record)">质押记录</a-button>
      </template>
      <template slot="ftp" slot-scope="{record}">
        <a-button shape="round" icon="setting" size="small" @click="showFipVis(record)">FTP设置</a-button>
      </template>
      <span slot="action" slot-scope="{record}">
        <!-- <a-divider type="vertical" /> -->
        <a @click="getJiaoYiList(record)">交易记录</a>
      </span>
    </advance-table>
    <span>总共 {{ dataSource.length }} 条</span>
    <!-- 转账 -->
    <!-- <a-modal v-model="transferModal" title="转账" @ok="transferOk('ruleForm')">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item ref="transferAddress" prop="transferAddress" label="转资地址：" placeholder="请输入资产转入的钱包地址">
            <a-input v-model="form.transferAddress"></a-input>
          </a-form-model-item>
        <a-form-model-item ref="transferMoney" prop="transferMoney" label="金额：" placeholder="请输入资产转入的金额">
            <a-input v-model="form.transferMoney"></a-input>
          </a-form-model-item>
      </a-form-model>
    </a-modal> -->
    <!-- 归集资产 -->
    <a-modal v-model="dialogGroup.one" title="归集资产" @ok="oneOk">
      <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
        <a-form-model-item label="转资地址">
          <a-input v-model="dialogOneParams" placeholder="请输入资产转入的钱包地址"></a-input>
        </a-form-model-item>
        <a-form-model-item label="是否定额">
          <a-switch v-model="isAmount" />
        </a-form-model-item>
        <a-form-model-item label="定额数量">
          <a-input v-model="amountNum" :disabled="!isAmount" placeholder="请输入定额数量"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 归集资产 end -->
    <!-- 质押交易 -->
    <a-modal v-model="dialogGroup.two" title="质押交易" :confirm-loading="twoLoad" @ok="twoOk">
      <a-form-model>
        <a-form-model-item label="UENC：" placeholder="请输入质押金额">
            <a-input v-model="dialogTwoParams"></a-input>
          </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 质押交易 end -->
    <!-- 批量设置燃料费 -->
    <a-modal v-model="dialogGroup.three" title="批量设置燃料费" @ok="threeOk">
      <a-form-model>
        <a-form-model-item label="设置燃料费：" placeholder="请输入燃料费">
            <a-input v-model="dialogThreeParams"></a-input>
          </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 批量设置燃料费 end -->
    <!-- 修改密码 -->
    <a-modal v-model="dialogGroup.four" title="修改密码" @ok="fourOk">
      <a-form-model>
        <a-form-model-item label="修改密码" placeholder="请输入密码">
            <a-input v-model="dialogFourParams"></a-input>
          </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 修改密码 end -->
    <!-- 解锁 -->
    <a-modal v-model="dialogGroup.five" title="解锁" :confirm-loading="fiveLoad" @ok="fiveOk">
      <a-form-model>
        <a-form-model-item label="密码" placeholder="请输入密码">
            <a-input v-model="dialogFiveParams"></a-input>
          </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 解锁 end -->
    <!-- 质押记录抽屉 -->
    <a-drawer
      placement="right"
      :closable="true"
      :visible="drawerStatus"
      :width="700"
      :headerStyle="{
        'font-weight': 600
      }"
      @close="drawerStatus = false"
    >
    <template slot="title">
      <div style="font-weight: 600">矿机详情</div>
    </template>
      <!-- 卡片 -->
      <div>
        <a-row style="maring-top: 15px; margin-bottom: 15px">
          <a-col :span="12">
            <label>本地IP：</label>
            <span class="shenlue">{{ cardJson.ipPort }}</span>
          </a-col>
        </a-row>
        <a-row style="maring-top: 15px; margin-bottom: 15px">
          <a-col :span="24">
            <label>钱包地址：</label>
            <span class="shenlue">{{ cardJson.address }}</span>
          </a-col>
        </a-row>
        <!-- <a-row style="maring-top: 15px; margin-bottom: 15px">
          <a-col :span="24">
            <label>私钥：</label>
            <span class="shenlue">{{ cardJson.privateKey }}</span>
          </a-col>
        </a-row> -->
        <a-row style="maring-top: 15px; margin-bottom: 15px">
          <a-col :span="12">
            <label>余额：</label>
            <span class="shenlue">{{ cardJson.balance }}</span>
          </a-col>
          <a-col :span="12">
            <label>访问状态：</label>
            <span :class="[cardJson.syncFlag ?  'point': 'point2']">{{ formatter(cardJson.syncFlag) }}</span>
          </a-col>
        </a-row>
        <a-row style="maring-top: 15px; margin-bottom: 15px">
          <a-col :span="12">
            <label>区块高度：</label>
            <span class="shenlue">{{ cardJson.millHeight }}</span>
          </a-col>
          <a-col :span="12">
            <label>燃料费：</label>
            <span class="shenlue">{{ cardJson.serviceFee }}</span>
          </a-col>
        </a-row>
        <a-row style="maring-top: 15px; margin-bottom: 15px">
          <a-col :span="12">
            <label>质押状态：</label>
            <span :class="[cardJson.isPledge == '1' ?  'point': 'point2']">{{ formatterIsPledge(cardJson.isPledge) }}</span>
          </a-col>
          <a-col :span="12">
            <label>重启设备：</label>
            <a-button size="small" shape="round" type="primary" @click="resetFacility">重启</a-button>
          </a-col>
        </a-row>
      </div>
      <!-- 表格 -->
      <div>
        <a-table
          :columns="tradeArray"
          :data-source="tradeData"
          :pagination="{
            current: current,
            pageSize: tradePageSize,
            total: tradeTotal,
          }"
          @change="tradeChange"
        >
          <template slot="txhash" slot-scope="text">
            <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ text }}</div>
          </template>
          
           <template slot="action" slot-scope="text, record">
            <a-button type="primary" shape="round" size="small"
             @click="unlockPledge(record)">解质押</a-button>
          </template>
        </a-table>
      </div>
      <!-- 底部按钮 -->
     <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        
        <a-button :style="{ marginRight: '8px' }" @click="cloasDrawer">
          取消
        </a-button>
        <a-button type="primary" @click="cloasDrawer">
          提交
        </a-button>
      </div>
      <!-- 底部按钮-end -->
    </a-drawer>
    <!-- 质押记录抽屉-end -->
    <!-- 交易记录抽屉 -->
    <a-drawer 
      title="交易记录"
      placement="right"
      :closable="true"
      :visible="jiaoYiVis"
      :width="900"
      :bodyStyle="{ marginBottom: '30px'}"
      @close="jiaoYiVis = false"
    >
      <a-descriptions 
        style="margin: 10px 0 10px 0" 
        v-for="(item, index) in jiaoYiList" 
        :key="index" 
        bordered 
        :column="3" 
        size="small"
      >
        <a-descriptions-item label="交易时间" :span="2">
          {{moment(item.time/1000).format('YYYY-MM-DD HH:mm') }}
        </a-descriptions-item>
        <a-descriptions-item label="交易额" :span="2">
          {{ item.amount }}
        </a-descriptions-item>
        <a-descriptions-item label="交易类型" :span="2">
          <a-tag>{{ item.type | jiaoYiType }}</a-tag>
        </a-descriptions-item>
         <a-descriptions-item label="交易hash" :span="2">
          {{ item.txhash }}
        </a-descriptions-item>
      </a-descriptions>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-pagination v-model="jiaoYiPagination.current" :total="jiaoYiPagination.total" show-less-items @change="jiaoYiFenye" />
      </div>
    </a-drawer>
    <!-- 弹窗 -->
    <a-modal
      title="私钥路径设置"
      :visible="showModal"
      @ok="handleOk"
      @cancel="handleCancel"
    >
    <a-form :form="form" >
     <a-form-item label="私钥储存路径:" >
        <a-select
          v-decorator="['uPath',{ rules: [{ required: true, message: '私钥储存路径不能为空!' }] }]"
          style="width: 100%"
          placeholder="请选择权限"
        >
        <a-select-option value="D">D</a-select-option>
        <a-select-option value="E">E</a-select-option>
        <a-select-option value="F">F</a-select-option>
        <a-select-option value="G">G</a-select-option>
        <a-select-option value="H">H</a-select-option>
        <a-select-option value="I">I</a-select-option>
      </a-select>
    </a-form-item>
     </a-form>
    </a-modal>
    <!-- 单台矿机连接参数 -->
    <a-modal
      title="设置矿机连接参数"
      :visible="ftpVis"
      :confirm-loading="ftpLoad"
      @ok="setFTP"
      @cancel="ftpVis = false"
    >
      <a-form-model size="small" :model="ftpForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
        <a-form-model-item label="钱包地址">
          <a-input :disabled="true" v-model="ftpForm.address" />
        </a-form-model-item>
        <a-form-model-item label="FTP密码">
          <a-input v-model="ftpForm.ftpPwd" />
        </a-form-model-item>
        <a-form-model-item label="FTP端口号">
          <a-input v-model="ftpForm.ftpPort" />
        </a-form-model-item>
         <a-form-model-item label="私钥">
           <a-switch v-model="ftpForm.isPrivate" checked-children="开" un-checked-children="关" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import AdvanceTable from '@/components/table/advance/AdvanceTable'
  import Clipboard from 'clipboard'
  import {
    refresh,
    batchSendTranstion,
    batchRedeemMill,
    rollbackBlock,
    sendQuotaTranstion,
    pledgeMill,
    batchSetMillFee,
    batchUpdatePwd,
    pledgeList,
    deBlockMill,
    tradeList,
    setMillParams,
    resetMill,
    redeemMill,
    setUPath
  } from '@/services/myDevice'
  import {
    mapGetters , mapMutations
  } from 'vuex'
import moment from 'moment'
import { de } from 'date-fns/locale'
  export default {
    name: 'Table',
    components: {
      AdvanceTable
    },
    filters: {
      statusStr(val) {
        switch (val) {
          case '0':
            return '未质押'
          case '1':
            return '已质押'
        }
      },
      subTen(val) {
        let result = val.substring(0,10)
        if(result.length == 0) {
          return ''
        } else {
          return result + '...'
        }
      },
      jiaoYiType(val) {
        switch(val) {
          case 'TxInfoType_Unknown':
            return '未知'
          case 'TxInfoType_Originator':
            return '交易发起方'
          case 'TxInfoType_Receiver':
            return '交易接收方'
          case 'TxInfoType_Gas':
            return '手续费奖励'
          case 'TxInfoType_Award':
            return '区块奖励'
          case 'TxInfoType_Pledge':
            return '质押'
          case 'TxInfoType_RedeemPledge':
            return '解除质押'
          case 'TxInfoType_PledgedAndRedeemed':
            return '质押但已解除'
        }
      },
      hideInfo(val) {
        if(val.length == 0) {
          return val
        } else {
          var reg = /^[0-9]*$/;
          let str = val.replace(reg,"******");
          return str
        }
      },
      hidePrKey(val) {
        if(val.length == 0) {
          return val
        } else {
          return '************'
        }
      }
    },
    data() {
      let checkMoney = (rule, value, callback) => {
        if(Number(value) > Number(this.transferParams.balance)) {
          callback(new Error('转入金额不能超过余额'))
        } else if(!value) {
          return callback(new Error('请输入金额'))
        } else {
          callback()
        }
      }
      return {
        moment,
        twoLoad: false,
        fiveLoad: false,
        drawerStatus: false, // 抽屉控制
        jiaoYiVis: false, // 交易抽屉
        ftpVis: false,
        loading: false,
        ftpLoad: false,
        showModal:false, //设置本地UPath 控制
        form:this.$form.createForm(this, { name: 'set_uPath' }),
        uPath:'',
        page: 1,
        pageSize: 100,
        total: 0,
        columns: [
          {
            key: 'ipPort',
            title: 'IP',
            dataIndex: 'ipPort',
            width: 160,
            searchAble: true,
            align:'center',
            scopedSlots: {
              customRender: 'local_ip'
            },
          },
          // {
          //   title: '昵称',
          //   dataIndex: 'nickname'
          // },
          {
            key: 'address',
            title: '钱包地址',
            dataIndex: 'address',
            width: 120,
            align:'center',
            scopedSlots: { customRender: 'address' },
            ellipsis: true,
            customCell: (record) => {
            return {
              style: {
               width: '100px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow:'ellipsis',
                cursor:'pointer'
              }
            }
          }
          },
          {
            key: 'privateKey',
            title: '私钥',
            dataIndex: 'privateKey',
            align:'center',
            scopedSlots: { customRender: 'privateKey' },
            ellipsis: true,
            customCell: (record) => {
              return {
                style: {
                 width: '100px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow:'ellipsis',
                cursor:'pointer'
                }
              }
            }
          },
          {
            key: 'balance',
            title: '余额',
            dataIndex: 'balance',
            align:'center'
          },
          // {
          //   searchAble: true,
          //   title: '访问状态',
          //   dataIndex: 'status',
          //   dataType: 'select',
          //   search: {
          //     selectOptions: [
          //       {title: '已下单', value: 1},
          //       {title: '已付款', value: 2},
          //       {title: '已审核', value: 3},
          //       {title: '已发货', value: 4}
          //     ]
          //   }
          // },
          {
            key: 'millHeight',
            title: '区块高度',
            dataIndex: 'millHeight',
            align:'center',
            width: 80,
            scopedSlots: {
              customRender: 'millHeight'
            },
            // customCell: (record) => {
            //   return {
            //     style: {
            //       fontWeight: 'bolder'
            //     }
            //   }
            // }
          },
          {
            key: 'serviceFee',
            title: '燃料费',
            width: 80,
            dataIndex: 'serviceFee',
            align:'center'
          },
          {
            key: 'password',
            title: '密码',
            dataIndex: 'password',
            align:'center',
            scopedSlots: { customRender: 'password' },
          },
          {
            key: 'isPledge',
            title: '质押状态',
            dataIndex: 'isPledge',
            align:'center',
            scopedSlots: {
              customRender: 'isPledge'
            },
          },
          {
            key: 'pledge',
            title: '质押记录',
            dataIndex: 'pledge',
            align:'center',
            scopedSlots: {
              customRender: 'pledge'
            },
          },
          // {
          //   key: 'ftp',
          //   title: 'FTP设置',
          //   dataIndex: 'ftp',
          //   align:'center',
          //   scopedSlots: {
          //     customRender: 'ftp'
          //   },
          // },
          {
            key: 'action',
            title: '操作',
            width: 140,
            fixed: 'right',
            dataIndex: 'action',
            align:'center',
            scopedSlots: {
              customRender: 'action'
            },
          }
        ],
        dataSource: [],
        conditions: {},
        selectedRowKeys: [], // 选中的行
        selectedRows: [], // 选中的数据
        dialogGroup: {
          one: false,
          two: false,
          three: false,
          four: false,
          five: false,
        },
        dialogOneParams: '',
        isAmount: false,
        amountNum: '',
        dialogTwoParams: '',
        dialogThreeParams: '',
        dialogFourParams: '',
        dialogFiveParams: '',
        // 抽屉
        cardJson: {
          address: '',
          balance: '',
          createTime: '',
          hasKeys: '',
          id: '',
          ip: '',
          isPledge: '',
          ipPort: '',
          millHeight: '',
          password: '',
          privateKey: '',
          serviceFee: '',
          status: '',
          syncFlag: '',
        },
        current: 1,
        tradePageSize: 100,
        tradeTotal: 0,
        tradeArray: [{
          key: 'time',
          title: '交易时间',
          dataIndex: 'time',
          align:'center'
        }, {
          key: 'amount',
          title: '交易数额',
          dataIndex: 'amount',
          align:'center'
        },
         {
          key: 'action',
          title: '操作',
          align:'center',
          scopedSlots: {
            customRender: 'action'
          }
         }],
        tradeData: [],
        tradeAddress: '',
        jYParams: {},
        jiaoYiList: [],
        jiaoYiPagination: {
          current: 1,
          total: 0
        },
        // ftp
        ftpForm: {
          address: '',
          isPrivate: false,
          ftpPwd: '',
          ftpPort: ''
        }
      }
    },
    computed: {
      ...mapGetters('account', ['user']),
    },
    mounted() {
      if(!this.user.uPath){
        this.showModal = true
      }
      this.getGoodList()
      // this.getColumns()
    },
    methods: {
      ...mapMutations('account', ["setUser"]),
      /**
       * 重启矿机
       */
      resetFacility(){
        const {isPrivate , ip , ftpPort , password} = this.cardJson
        let data = new FormData()
        data.append('isPrivate',isPrivate)
        data.append('ip',ip)
        data.append('ftpPort',ftpPort)
        data.append('password',password)
        resetMill(data).then(res=>{
          if(res.data.code === 200){
            this.$message.success(res.data.result)
            this.cloasDrawer()
            this.getGoodList()
          }else{
            this.$message.error(res.data.result)
          } 
        })
      },
      /**
       * 矿机解质押
       */
      unlockPledge(record){
        const {isPrivate , address , protoPort ,password} = this.cardJson
        let data = new FormData()
        data.append('password',password)
        data.append('utxo',record.utxo)
        data.append('isPrivate',isPrivate)
        data.append('address',address)
        data.append('protoPort',protoPort)
        redeemMill(data).then(res=>{
          if(res.data.code === 200){
            this.$message.success(res.data.result)
            this.getTradeList(this.cardJson)
          }else{
            this.$message.error(res.data.result)
          } 
        })
      },
      /**
       * @desc 点击复制
       */
      copyCode() {
        let clipboard = new Clipboard('.copyBtn')
         clipboard.on('success', e => {  
            this.$message.success("复制成功");//这里你如果引入了elementui的提示就可以用，没有就注释即可
              // 释放内存  
              clipboard.destroy()  
            })  
            clipboard.on('error', e => {  
            // 不支持复制  
            this.$message.warning('该浏览器不支持自动复制')  
            // 释放内存  
            clipboard.destroy()  
          })  
      },
      getGoodList() {
        this.loading = true
        let formData = new FormData()
        formData.append('userId', this.user.userId)
        formData.append('uPath', this.user.uPath)
        
        refresh(formData)
        .then(this.renderTable)
        .catch(() => {
          this.loading = false
        })
      },
      renderTable(res) {
        if (res.data.code == 200) {
          let array = []
          res.data.result.millList.forEach((item, index) => {
            let obj = {
              key: index,
              address: item.address,
              balance: item.balance,
              createTime: item.createTime,
              hasKeys: item.hasKeys,
              id: item.ip,
              ip: item.ip,
              isPledge: item.isPledge,
              ipPort: item.ipPort,
              millHeight: item.millHeight,
              market: res.data.result.market,
              heightCha: Math.abs(Number(item.millHeight) - Number(res.data.result.market)),
              password: item.password,
              privateKey: item.privateKey,
              serviceFee: item.serviceFee,
              status: item.status,
              syncFlag: item.syncFlag,
              protoPort: item.protoPort,
              rpcPort: item.rpcPort,
              ftpPwd: item.ftpPwd,
              ftpPort: item.ftpPort,
              isPrivate: item.isPrivate,
              passStatus: true,
              keyStatus: false,
            }
            array.push(obj)
          })
          this.dataSource = array
          this.selectedRowKeys = []
          this.selectedRows = []
          this.loading = false
        }
      },
      /**
       * @desc 表格复选
       */
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRows = selectedRows;
      },
      /**
       * @desc 控制模态框状态
       */
      showDialog(e) {
        let _this = this
        switch (e) {
          case 'one':
            this.dialogGroup.one = true
            break;
          case 'two':
            this.dialogGroup.two = true
            break;
          case 'three':
            this.dialogGroup.three = true
            break;
          case 'four':
            this.dialogGroup.four = true
            break;
          case 'five':
            this.dialogGroup.five = true
             break;
          case 'six':
             this.batchUnTrade()
            break;
          case 'seven':
             this.batchBack()
            break;
        }
      },
      getColumns() {

      },
      onSearch(conditions, searchOptions) {
        this.page = 1
        this.conditions = conditions
        this.getGoodList()
      },
      onSizeChange(current, size) {
        this.page = 1
        this.pageSize = size
        this.getGoodList()
      },
      onRefresh(conditions) {
        this.conditions = conditions
        this.getGoodList()
      },
      onReset(conditions) {
        this.conditions = conditions
        this.getGoodList()
      },
      onPageChange(page, pageSize) {
        this.page = page
        this.pageSize = pageSize
        this.getGoodList()
      },
      handleOk(){
          this.form.validateFields((error, values) => {
            const user = this.user
            user.uPath = values.uPath

            let formData = new FormData()
            formData.append('userId', this.user.userId)
            formData.append('uPath', user.uPath)
            setUPath(formData).then((res) => {
              if(res.data.code == 200) {
                this.$message.success(res.data.result)
                this.setUser(user)
                this.handleCancel()
              } else {
                this.$message.warning(res.data.result)
              }
            })

        });
      },
      /**
       * 批量回滚
       */
      batchBack(){
          let ipList=[],sourceIP
          if(this.selectedRows == 0){
          this.$message.info('请选择至少1项');
          return false
         }
          let array = this.selectedRows.map(item=>{
          if(item.address && item.heightCha > 5){
            ipList.push(item.ip)
            return item
          }
        }).filter(Boolean)
        this.dataSource.forEach(item=>{
          if(item.heightCha < 5){
            sourceIP = item.ip
          }
        })
         if(array.length == 0){
          this.$message.info('选中暂无可回滚！未质押和区块高度正常无法回滚！');
          return false
         }
         if(!sourceIP){
          this.$message.info('暂无可同步矿机！');
          return false
         }
          let formData = new FormData()
           formData.append('ipList',ipList)
           formData.append('sourceIP',sourceIP)
           formData.append('userId', this.user.userId)
           rollbackBlock(formData).then(res=>{
             if (res.data.code == 200) {
              this.$message.success(res.data.result)
               this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
            }
           })
      },
      /**
       * 批量解质押
       */
      batchUnTrade(){
        let ipList=[],protoPortList=[],passwordList=[],addressList = []
        if(this.selectedRows == 0){
          this.$message.info('请选择至少1项');
          return false
        }
        let array = this.selectedRows.map(item=>{
          if(item.address && item.heightCha > 5){
            ipList.push(item.ip)
            protoPortList.push(item.protoPort)
            passwordList.push(item.password)
            addressList.push(item.address)
            return item
          }
        }).filter(Boolean)
        if(array.length == 0){
          this.$message.info('选中暂无可解质押！未质押和区块高度异常无法解质押！');
          return false
        }
        let formData = new FormData()
        formData.append('ipList',ipList)
        formData.append('protoPortList',protoPortList)
        formData.append('passwordList',passwordList)
        formData.append('addressList',addressList)
        batchRedeemMill(formData).then(res=>{
          if (res.data.code == 200) {
              this.$message.success(res.data.result)
               this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
            }
        })
      },
          /**
     * 关闭弹窗
     */
    handleCancel(){
      this.showModal = false
    },
      /**
       * @desc 第一个模态框ok
       */
      oneOk() {
        let _this = this
        let array = _this.selectedRows

        if(array.length == 0) {
          this.$message.info('请选择至少1项');
          return false
        }

        let heightResult = this.checkMillHeight(array)
        if(heightResult) {
          this.$message.error('选中项中包含主网高度异常数据')
        }
        
        let ipList = ''
        let passwordList = ''
        let fromList = ''
        let protoPortList = ''
        let rpcPortList = ''

        for(let i = 0; i < array.length; i++) {
          ipList += array[i].ip + ','
          passwordList += array[i].password + ','
          fromList += array[i].address + ','
          protoPortList += array[i].protoPort + ','
          rpcPortList += array[i].rpcPort + ','
        }
        ipList = ipList.substring(0, ipList.length - 1);
        passwordList = passwordList.substring(0, passwordList.length - 1);
        fromList = fromList.substring(0, fromList.length - 1);
        protoPortList = protoPortList.substring(0, protoPortList.length - 1);
        rpcPortList = rpcPortList.substring(0, rpcPortList.length - 1);

        let formData = new FormData()
        formData.append('toAddress', _this.dialogOneParams)
        formData.append('ipList', ipList)
        formData.append('fromList', fromList)
        formData.append('passwordList', passwordList)
        formData.append('protoPortList', protoPortList)
        formData.append('rpcPortList', rpcPortList)
        formData.append('uPath', this.user.uPath)
        if(this.isAmount) {
          formData.append('amount', this.amountNum)
          sendQuotaTranstion(formData).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.result)
              this.dialogGroup.one = false
              this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
            }
          })
        } else {
          batchSendTranstion(formData).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.result)
              this.dialogGroup.one = false
              this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
            }
          }) 
        }
      },
      /**
       * @desc 第二个模态框ok
       */
      twoOk() {
        let _this = this
        this.twoLoad = true
        let array = _this.selectedRows

        if(array.length == 0) {
          this.$message.info('请选择至少1项');
          this.twoLoad = false
          return false
        }

        let heightResult = this.checkMillHeight(array)
        if(heightResult) {
          this.$message.error('选中项中包含主网高度异常数据')
        }

        let addressList = ''
        let ipList = ''
        let passwordList = ''
        let protoPortList = ''

        for(let i = 0; i < array.length; i++) {
          if (array[i].address !== '') {
             addressList += array[i].address + ','
          }
          ipList += array[i].ip + ','
          if (array[i].password !== '') {
            passwordList += array[i].password + ','
          }
          protoPortList += array[i].protoPort + ','
        }

        addressList = addressList.substring(0, addressList.length - 1);
        ipList = ipList.substring(0, ipList.length - 1);
        passwordList = passwordList.substring(0, passwordList.length - 1);
        protoPortList = protoPortList.substring(0, protoPortList.length - 1);

        let formData = new FormData()
        formData.append('amount', _this.dialogTwoParams)
        formData.append('addressList', addressList)
        formData.append('ipList', ipList)
        formData.append('passwordList', passwordList)
        formData.append('protoPortList', protoPortList)

        pledgeMill(formData).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.result)
            this.dialogGroup.two = false
            this.twoLoad = false
            this.getGoodList()
          } else {
            this.$message.warning(res.data.result)
            this.twoLoad = false
          }
        })
        .catch(() => { this.twoLoad = false })
      },
      /**
       * @desc 第三个模态框ok
       */
      threeOk() {
        let _this = this
        let array = _this.selectedRows
        if(array.length == 0) {
          this.$message.info('请选择至少1项');
          return false
        }

        let heightResult = this.checkMillHeight(array)
        if(heightResult) {
          this.$message.error('选中项中包含主网高度异常数据')
        }

        let ipList = ''
        let protoPortList = ''

        for(let i = 0; i < array.length; i++) {
          ipList += array[i].ip + ','
          protoPortList += array[i].protoPort + ','
        }
        ipList = ipList.substring(0, ipList.length - 1);
        protoPortList = protoPortList.substring(0, protoPortList.length - 1);

        let formData = new FormData()
        formData.append('ipList', ipList)
        formData.append('fee', _this.dialogThreeParams)
        formData.append('userId', _this.user.userId)
        formData.append('protoPortList', protoPortList)

        batchSetMillFee(formData).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.result)
              this.dialogGroup.three = false
              this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
            }
        })  
      },
      /**
       * @desc 第四个模态框ok
       */
      fourOk() {
        let _this = this
        let array = _this.selectedRows
        if(array.length == 0) {
          this.$message.info('请选择至少1项');
          return false
        }

        let heightResult = this.checkMillHeight(array)
        if(heightResult) {
          this.$message.error('选中项中包含主网高度异常数据')
        }

        let oldPassList = ''
        let ipList = ''
        let addressList = ''
        for(let i = 0; i < array.length; i++) {
          oldPassList += array[i].password + ','
          ipList += array[i].ipPort + ','
          addressList += array[i].address + ','
        }
        oldPassList = oldPassList.substring(0, oldPassList.length - 1);
        ipList = ipList.substring(0, ipList.length - 1);
        addressList = addressList.substring(0, addressList.length - 1);

        let formData = new FormData()
        formData.append('ipList', ipList)
        formData.append('new_pass', _this.dialogFourParams)
        formData.append('oldPassList', oldPassList)
        formData.append('addressList', addressList)

        batchUpdatePwd(formData).then((res) => {
          if (res.data.code == 200) {
              this.$message.success(res.data.result)
              this.dialogGroup.four = false
              this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
            }
        })  
      },

      fiveOk() {
        let _this = this
        _this.fiveLoad = true
        let array = _this.selectedRows
        if(array.length == 0) {
          this.$message.info('请选择至少1项');
          this.fiveLoad = false
          return false
        }

        let protoPortList = ''
        let rpcPortList = ''

        for(let i = 0; i < array.length; i++) {
          protoPortList += array[i].protoPort + ','
          rpcPortList += array[i].rpcPort + ','
        }
        protoPortList = protoPortList.substring(0, protoPortList.length - 1);
        rpcPortList = rpcPortList.substring(0, rpcPortList.length - 1);


        let formData = new FormData()
        formData.append('userId', this.user.userId)
        formData.append('ipList', this.selectedRowKeys.join(','))
        formData.append('protoPortList', protoPortList)
        formData.append('rpcPortList', rpcPortList)
        formData.append('password', _this.dialogFiveParams)
        formData.append('userInfo', this.user.userInfo)
        formData.append('uPath', this.user.uPath)

        deBlockMill(formData).then((res) => {
          if (res.data.code == 200) {
              this.$message.success(res.data.result)
              this.dialogGroup.five = false
              this.fiveLoad = false
              this.getGoodList()
            } else {
              this.$message.warning(res.data.result)
              this.fiveLoad = false
            }
        })  
      },
      /**
       * @desc 显示抽屉
       */
      showDrawer(e, o) {
        this.drawerStatus = true
        this.tradeAddress = o.address
        this.getTradeList(o)
        console.log(e, o)
        this.cardJson.isPrivate = o.isPrivate
        this.cardJson.ftpPort = o.ftpPort
        this.cardJson.address = o.address
        this.cardJson.balance = o.balance
        this.cardJson.createTime = o.createTime
        this.cardJson.hasKeys = o.hasKeys
        this.cardJson.id = o.id
        this.cardJson.ip = o.ip
        this.cardJson.isPledge = o.isPledge
        this.cardJson.ipPort = o.ipPort
        this.cardJson.millHeight = o.millHeight
        this.cardJson.password = o.password
        this.cardJson.privateKey = o.privateKey
        this.cardJson.serviceFee = o.serviceFee
        this.cardJson.status = o.status
        this.cardJson.syncFlag = o.syncFlag
      },
      /**
        @desc 关闭抽屉
      */
      cloasDrawer() {
        this.drawerStatus = false
      },
      /**
       * @desc 获取质押记录
       */
      getTradeList(record) {
        let pageNum = this.current
        let pageSize = 8
        let formData = new FormData()
        formData.append('address', record.address)
        formData.append('ip', record.ip)
        formData.append('protoPort', record.protoPort)
        pledgeList(formData).then((res) => {
          if(res.data.code == 200) {
            // this.tradeTotal = res.data.result.detailCount
            // this.tradeData = res.data.result.detailList
             this.tradeData = res.data.result
          }
        })
      },
      /**
       * @desc 质押表分页
       */
      tradeChange(pagination) {
        this.current = pagination.current
      },
      formatter(flag) {
        let obj = {
          true: '正常',
          false: '异常'
        }
        return obj[flag]
      },
      formatterIsPledge(e) {
        let obj = {
          '1': '已质押',
          '0': '未质押'
        }
        return obj[e]
      },
      /**
       * @desc 单/批量解锁矿机
       */
      toUnlock() {
        let params = this.selectedRows
        let ipList = this.selectedRowKeys.join(',')
        let formData = new FormData()
        formData.append('ipList', ipList)
        formData.append('userId', this.user.userId)
        // deBlockMill()
      },
      /**
       * @desc 解质押
       */
      toRedeemMill(record) {

      },
      /**
       * @desc 获取交易记录
       */
      getJiaoYiList(record) {
        this.jiaoYiVis = true
        let formData = new FormData()
        this.jYParams = record
        formData.append('ip', record.id)
        formData.append('protoPort', record.protoPort)
        formData.append('address', record.address)
        formData.append('txhash', '')
        formData.append('count', 10)
        tradeList(formData).then((res) => {
          if(res.data.code == 200) {
            this.jiaoYiList = res.data.result.list
          }
        })
      },
      jiaoYiFenye() {
        let record = this.jYParams
        let formData = new FormData()
        formData.append('ip', record.id)
        formData.append('protoPort', record.protoPort)
        formData.append('address', record.address)
        formData.append('txhash', record[record.length - 1].txhash)
        formData.append('count', 10)
        tradeList(formData).then((res) => {
          if(res.data.code == 200) {
            this.jiaoYiList = res.data.result.detailList
          }
        })
      },
      /**
       * @desc 显示FTP
       */
      showFipVis(record) {
        this.ftpVis = true
        this.ftpForm.isPrivate = record.isPrivate == '1'
        this.ftpForm.address = record.address
        this.ftpForm.ftpPwd = record.ftpPwd
        this.ftpForm.ftpPort = record.ftpPort == 0 ? '' : record.ftpPort
      },
      /**
       * @desc 设置FTP
       */
      setFTP() {
        this.ftpLoad = true
        let formData = new FormData()
        formData.append('address', this.ftpForm.address)
        formData.append('ftpPwd', this.ftpForm.ftpPwd)
        formData.append('ftpPort', this.ftpForm.ftpPort)
        formData.append('isPrivate', this.ftpForm.isPrivate)
        setMillParams(formData).then(res => {
          if(res.data.code == 200) {
            this.$message.success(res.data.result)
            this.ftpVis = false
            this.ftpLoad = false
          } else {
            this.ftpLoad = false
          }
        })
      },
      showPass(e, index) {
        this.dataSource[index].passStatus = true
      },
      hidePass(e, index) {
        this.dataSource[index].passStatus = false
      },
      showKey(e, index) {
        this.dataSource[index].keyStatus = true
      },
      hideKey(e, index) {
        this.dataSource[index].keyStatus = false
      },
      /**
       * @desc 检查矿机高度是否合规
       */
      checkMillHeight(array) {
        let result = false
        array.forEach((item) => {
          if(item.heightCha > 5) {
            result = true
            return false
          }
        })
        return result
      }
    }
  }
</script>

<style scoped lang="less">
  .table {
    background-color: @base-bg-color;
    padding: 24px;
  }
  .point {
    margin-left: 10px;
    &::before{
        position: absolute;
        content: "";
        top: 8px;
        margin-left: -10px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: greenyellow;
    }
  }
  .point2 {
    margin-left: 10px;
    &::before{
        position: absolute;
        content: "";
        top: 8px;
        margin-left: -10px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: red;
    }
  }
  .shenlue {
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }
  .a-table {
    
  }
</style>